﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;

namespace WeiXinUtils
{
    public class HttpsUtils
    {
        public static string Get(string Url)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            WebRequest request = WebRequest.Create(Url);
            request.Method = "get";
            WebResponse response = request.GetResponse();
            string responseStr = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseStr = reader.ReadToEnd();
            }
            return responseStr;
        }

        public static T Get<T>(string Url) where T:class
        {
            string responseStr = Get(Url);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseStr);
        }

        public static string Post(string Url, string Data)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            WebRequest request = WebRequest.Create(Url);
            request.Method = "post";
            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(Data);
            }
            WebResponse response = request.GetResponse();
            string responseStr = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                responseStr = reader.ReadToEnd();
            }
            return responseStr;
        }

        public static T Post<T>(string Url, string Data)
        {
            string responseStr = Get(Url);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseStr);
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受     
        }  
    }
}